import { Router } from "jsr:@oak/oak/router";
import { getAuth } from "../services/auth.ts";
import type { ApiResponse, LoginResponseData } from "../shared/types.ts";
import { AuthErrors } from "../errors/AppError.ts";

const router = new Router();

router.post("/api/auth/login", async (ctx) => {
  const body = await ctx.request.body.json();
  const { username, password } = body;
  
  try {
    const auth = getAuth();
    const authResult = await auth.authenticate(username, password);
    
    const response: ApiResponse<LoginResponseData> = {
      success: true,
      data: {
        token: authResult.token,
        user: {
          id: authResult.user.id,
          username: authResult.user.username
        }
      }
    };
    
    ctx.response.body = response;
  } catch (error) {
    if (error instanceof Error && error.name === "AuthError") {
      throw AuthErrors.InvalidCredentials();
    }
    throw error;
  }
});

export default router; 